$( document ).ready(function() {
      var hostName = window.location.hostname;
      var left = CodeMirror.fromTextArea(document.getElementById("left-code"), {
                    lineNumbers: true,
                    mode: "text/x-csrc",
                    matchBrackets: true
      });

      var right = CodeMirror.fromTextArea(document.getElementById("right-code"), {
                    lineNumbers: true,
                    mode: "text/x-c++src",         
                    matchBrackets: true
      });
      left.setOption("theme", "twilight");
      right.setOption("theme", "twilight");
      $( "#convert" ).click(function() {
             $('#loading').show();
             var codeLines = left.lineCount();
             var sourceCode = [];
             var codeLine = "";
             for (var i = 0; i <= codeLines-1; i++) {
            		 sourceCode[i] = left.getLine(i);                
              };
              $.ajax({
                   dataType: "json",
                   url: "index.php/coder/get_code_convert",
                   type: "POST",
                   data: {
                	   src: JSON.stringify(sourceCode),
                   },
                   success: function(data){
                     $('#loading').hide();
                	   try{
                		   right.setValue(data.join('\n'));
                	   }catch(err){
                		   right.setValue(data);
                	   }
                   }
              });
      });
      
      
      var the = {
              use_codemirror: (!window.location.href.match(/without-codemirror/)),
              beautify_in_progress: false,
              editor: null // codemirror editor
          };

          function run_tests() {
              var st = new SanityTest();
              run_beautifier_tests(st, Urlencoded, js_beautify, html_beautify, css_beautify);
              JavascriptObfuscator.run_tests(st);
              P_A_C_K_E_R.run_tests(st);
              Urlencoded.run_tests(st);
              MyObfuscate.run_tests(st);
              var results = st.results_raw().replace(/ /g, '&nbsp;').replace(/\r/g, '·').replace(/\n/g, '<br>');
              $('#testresults').html(results).show();
          }


          function any(a, b) {
              return a || b;
          }

          function read_settings_from_cookie() {

          }

          function store_settings_to_cookie() {
              
          }

          function unpacker_filter(source) {
              var trailing_comments = '',
                  comment = '',
                  unpacked = '',
                  found = false;

              // cut trailing comments
              do {
                  found = false;
                  if (/^\s*\/\*/.test(source)) {
                      found = true;
                      comment = source.substr(0, source.indexOf('*/') + 2);
                      source = source.substr(comment.length).replace(/^\s+/, '');
                      trailing_comments += comment + "\n";
                  } else if (/^\s*\/\//.test(source)) {
                      found = true;
                      comment = source.match(/^\s*\/\/.*/)[0];
                      source = source.substr(comment.length).replace(/^\s+/, '');
                      trailing_comments += comment + "\n";
                  }
              } while (found);

              var unpackers = [P_A_C_K_E_R, Urlencoded, /*JavascriptObfuscator,*/ MyObfuscate];
              for (var i = 0; i < unpackers.length; i++) {
                  if (unpackers[i].detect(source)) {
                      unpacked = unpackers[i].unpack(source);
                      if (unpacked != source) {
                          source = unpacker_filter(unpacked);
                      }
                  }
              }

              return trailing_comments + source;
          }


          function beautify() {
             // console.log(right);
              if (the.beautify_in_progress) return;

             // store_settings_to_cookie();

              the.beautify_in_progress = true;

              var source = right.getValue(),
                  output,
                  opts = {};
    		/// console.log(source);
              opts.indent_size = $('#tabsize').val();
              opts.indent_char = opts.indent_size == 1 ? '\t' : ' ';
              opts.max_preserve_newlines = $('#max-preserve-newlines').val();
              opts.preserve_newlines = opts.max_preserve_newlines !== -1;
              opts.keep_array_indentation = $('#keep-array-indentation').prop('checked');
              opts.break_chained_methods = $('#break-chained-methods').prop('checked');
              opts.indent_scripts = $('#indent-scripts').val();
              opts.brace_style = $('#brace-style').val();
              opts.space_before_conditional = $('#space-before-conditional').prop('checked');
              opts.unescape_strings = $('#unescape-strings').prop('checked');
              opts.wrap_line_length = $('#wrap-line-length').val();
              opts.space_after_anon_function = true;

              if (looks_like_html(source)) {
                  output = html_beautify(source, opts);
              } else {
                  if ($('#detect-packers').prop('checked')) {
                      source = unpacker_filter(source);
                  }
                  output = js_beautify(source, opts);
              }
              if (right.editor) {
                  right.setValue(output);
              } else {
            	  right.setValue(output);
              }

              the.beautify_in_progress = false;
          }

          function looks_like_html(source) {
              // <foo> - looks like html
              // <!--\nalert('foo!');\n--> - doesn't look like html

              var trimmed = source.replace(/^[ \t\n\r]+/, '');
              var comment_mark = '<' + '!-' + '-';
              return (trimmed && (trimmed.substring(0, 1) === '<' && trimmed.substring(0, 4) !== comment_mark));
          }
      $('#convertabc').click(beautify);
});